
/**
 * The JobTrackerStatusQueryThread class
 *
 * @author  Joshua Kwan
 */

import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.KeeperException;
import java.util.List;

public class JobTrackerStatusQueryThread extends Thread {
	
	private final String JOBPOOL_PATH = PoolCreator.JOBPOOL_PATH;
	private ZkConnector zkc;
	private String hash;
	private String jobPath;
	private String userPath;
	
	public JobTrackerStatusQueryThread (ZkConnector zkc, String userID, String hash){
		System.out.println("JobTrackerStatusQueryThread created for " + userID + " to get password for " + hash);
        this.jobPath = JOBPOOL_PATH + "/" + userID + "/" + hash;
        this.userPath = "/" + userID;
        this.hash = hash;
		this.zkc = zkc;
	}
	
	public void run() {
		System.out.println("jobPath: " + jobPath + ", userPath: " + userPath);
		//check for existence of job in the jobpool
		if (zkc.exists(jobPath, false) == null) {
			zkc.atomicAppend("A job to process " + hash + " does not exist.", userPath);
			//System.out.println("Response: A job to process " + hash + " does not exist.");
		} else {
			ZooKeeper zk = zkc.getZooKeeper();
			Stat stat = new Stat();
			//check to see if there is a result for the job
			boolean responded = false;
			try {
				byte[] jobData = zk.getData(jobPath, false, stat); 
				if (jobData != null && !new String(jobData).equalsIgnoreCase("")){
					//we have a result
					zkc.atomicAppend("match found for " + hash + ": " + new String(jobData), userPath);
					//System.out.println("Response: match found for " + hash + ": " + new String(jobData));
					responded = true;
				} else {
					List<String> childList = zk.getChildren(jobPath, false);
					if (childList.size() == 0) {
						zkc.atomicAppend(hash + " produced no results.", userPath);
						//System.out.println("Response: " + hash + " produced no results.");
						responded = true;
					}
				}
				zk.delete(jobPath, stat.getVersion());
				//Check to see if the client has any children, if not, delete the client node within the jobpool
				//@TODO
			} catch (InterruptedException e) {
				System.out.println(e);
			} catch (KeeperException e) {
				System.out.println(e);
			}
			if (!responded) {
				//in progress
				zkc.atomicAppend(hash + " is being processed.", userPath);
				//System.out.println("Response: " + hash + " is being processed.");
			}
		}
	}
}